const { db } = require('../config/database');

class Message {
  // 创建消息
  static create(user_id, character_id, content, sender) {
    return new Promise((resolve, reject) => {
      const stmt = db.prepare('INSERT INTO messages (user_id, character_id, content, sender) VALUES (?, ?, ?, ?)');
      stmt.run(user_id, character_id, content, sender, function(err) {
        if (err) {
          reject(err);
        } else {
          resolve({
            id: this.lastID,
            user_id,
            character_id,
            content,
            sender
          });
        }
      });
      stmt.finalize();
    });
  }

  // 根据角色ID获取消息历史
  static findByCharacterId(character_id) {
    return new Promise((resolve, reject) => {
      db.all('SELECT * FROM messages WHERE character_id = ? ORDER BY created_at ASC', [character_id], (err, rows) => {
        if (err) {
          reject(err);
        } else {
          resolve(rows);
        }
      });
    });
  }

  // 根据用户ID和角色ID获取消息历史
  static findByUserAndCharacter(user_id, character_id) {
    return new Promise((resolve, reject) => {
      db.all('SELECT * FROM messages WHERE user_id = ? AND character_id = ? ORDER BY created_at ASC', [user_id, character_id], (err, rows) => {
        if (err) {
          reject(err);
        } else {
          resolve(rows);
        }
      });
    });
  }
}

module.exports = Message;